/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.skatiger.jrove.tag.ui;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.el.ELException;
import javax.el.VariableMapper;

import org.skatiger.jrove.JroveContext;
import org.skatiger.jrove.JroveException;
import org.skatiger.jrove.TagConfig;
import org.skatiger.jrove.TagHandler;
import org.skatiger.jrove.TemplateClient;
import org.skatiger.jrove.component.UIComponent;
import org.skatiger.jrove.el.VariableMapperWrapper;
import org.skatiger.jrove.tag.TagAttribute;
import org.skatiger.jrove.tag.TagAttributeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class CompositionHandler extends TagHandler implements
        TemplateClient {

    private static final Logger logger = LoggerFactory
            .getLogger(CompositionHandler.class);

    public final static String Name = "composition";

    protected final TagAttribute template;

    protected final Map<String, DefineHandler> handlers;

    protected final ParamHandler[] params;

    /**
     * @param config
     */
    public CompositionHandler(TagConfig config) {
        super(config);
        this.template = this.getAttribute("template");
        if (this.template != null) {
            this.handlers = new HashMap<String, DefineHandler>();
            Iterator<DefineHandler> defines = this
                    .findNextByType(DefineHandler.class);
            while (defines.hasNext()) {
                DefineHandler d = defines.next();
                this.handlers.put(d.getName(), d);
                logger.debug(tag + " found Define[" + d.getName() + "]");
            }
            List<ParamHandler> paramC = new ArrayList<ParamHandler>();
            Iterator<ParamHandler> paramsitr = this
                    .findNextByType(ParamHandler.class);
            while (paramsitr.hasNext()) {
                paramC.add(paramsitr.next());
            }
            if (paramC.size() > 0) {
                this.params = paramC.toArray(new ParamHandler[paramC.size()]);
            } else {
                this.params = null;
            }
        } else {
            this.params = null;
            this.handlers = null;
        }
    }

    public void apply(JroveContext ctx, UIComponent parent) throws IOException,
            JroveException, ELException {
        if (this.template != null) {

            VariableMapper orig = ctx.getVariableMapper();
            if (this.params != null) {
                VariableMapper vm = new VariableMapperWrapper(orig);
                ctx.setVariableMapper(vm);
                for (int i = 0; i < this.params.length; i++) {
                    this.params[i].apply(ctx, parent);
                }
            }

            ctx.extendClient(this);
            String path = null;
            try {
                path = this.template.getValue(ctx);
                ctx.includeJrove(parent, path);
                if (logger.isDebugEnabled()) {
                    logger.debug("ComponsitionHandler found template attribute, use template path "
                            + path);
                }
            } catch (IOException e) {
                throw new TagAttributeException(this.tag, this.template,
                        "Invalid path : " + path);
            } finally {
                ctx.popClient(this);
                ctx.setVariableMapper(orig);
            }
        } else {
            this.nextHandler.apply(ctx, parent);
        }
    }

    public boolean apply(JroveContext ctx, UIComponent parent, String name)
            throws IOException, JroveException, ELException {
        if (name != null) {
            if (this.handlers == null) {
                return false;
            }
            DefineHandler handler = this.handlers.get(name);
            if (handler != null) {
                handler.applyDefinition(ctx, parent);
                return true;
            } else {
                return false;
            }
        } else {
            this.nextHandler.apply(ctx, parent);
            return true;
        }
    }

}
